/**
 * @Author: 焦质晔
 * @Date: 2019/6/20
 * @Last Modified by: mikey.zhaopeng
 * @Last Modified time: 2019-11-28 14:08:33
 */
import {
  MessageBox,
  Notification,
  Message
} from 'element-ui';
import {
  queryEmployees
} from '@/api/index';
import config from '@/config';
import store from '@/store';
import moment from 'moment';

// 等待
export const sleep = async timeLen => {
  return new Promise(resolve => setTimeout(resolve, timeLen));
};

// 捕获基于 Promise 操作的异常
export const errorCapture = async promise => {
  try {
    const res = await promise;
    return [null, res];
  } catch (e) {
    return [e, null];
  }
};

// 需要确认的操作提示
export const confirmAction = async (msg = '确认进行此操作?', type = 'warning') => {
  return MessageBox.confirm(msg, '提示信息', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type
  });
};

// Notification 通知提示
export const notifyAction = async (msg = '暂无...', type = 'success', title = '提示信息') => {
  if (store.state.app.isNotifyMark) return;
  store.dispatch('app/createNotifyState', true);
  //1870-【大客户管理】-经销商大客户区域经理维护：保存时报错提示信息显示不全。-START
  Notification({
    title,
    message: `<div style="width: 250px;text-align: left;word-wrap: break-word;">${msg}</div>`,
    type,
    duration: config.notifyDuration,
    dangerouslyUseHTMLString: true
  });
  //1870-【大客户管理】-经销商大客户区域经理维护：保存时报错提示信息显示不全。-END
  await sleep(config.notifyDuration);
  store.dispatch('app/createNotifyState', false);
};

// Message 消息提示
export const messageAction = async (msg = '暂无...', type = 'info') => {
  if (store.state.app.isNotifyMark) return;
  store.dispatch('app/createNotifyState', true);
  Message({
    message: msg,
    showClose: true,
    type,
    duration: config.notifyDuration
  });
  await sleep(config.notifyDuration);
  store.dispatch('app/createNotifyState', false);
};

// 判断表单控件的值是否为空
export const isFormEmpty = val => {
  return typeof val === 'undefined' || val === '' || val === null;
};
// 判断是否为空
export const isEmpty = value => {
  return (Array.isArray(value) && value.length === 0) || (Object.prototype.isPrototypeOf(value) && Object.keys(value).length === 0);
};

export function getJsonTree(data, id = 'id', parentId = 'parentId') {
  data.forEach(function (item) {
    delete item.children;
  });
  const map = {};
  data.forEach(function (item) {
    map[item[id]] = item;
  });

  const val = [];
  data.forEach(function (item) {
    const parent = map[item[parentId]];

    if (parent) {
      (parent.children || (parent.children = [])).push(item);
    } else {
      val.push(item);
    }
  });

  return val;
}

// 限制编码
export function codeCheck(rule, value, callback) {
  if (value === undefined || value === '' || value === null) {
    callback();
  }
  var g = /^[\d|a-zA-Z_|-]{1,}$/;
  if (!g.test(value)) {
    callback(new Error('代码只能为字母数字!'));
  }
  callback();
}

/**
 * excel导出
 * @param {*} res
 */
export const exportExcelFile = (res = {}, name) => {
  const blob = new Blob([res], {
    type: 'application/octet-stream'
  }); //, { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' }
  const downloadElement = document.createElement('a');
  const href = window.URL.createObjectURL(blob);
  downloadElement.href = href;
  //cms合代码注意 兼容ie
  downloadElement.download = name + formatdate(new Date(), 1) + '.xls'; //文件名（自己随意设置）
  document.body.appendChild(downloadElement);
  if (!!window.ActiveXObject || 'ActiveXObject' in window || navigator.userAgent.indexOf('Edge') > -1) {
    window.navigator.msSaveOrOpenBlob(blob, downloadElement.download);
  } else {
    downloadElement.click();
  }
  //cms end
  document.body.removeChild(downloadElement); // 下载完成移除元素
  window.URL.revokeObjectURL(href);
};

/**
 * excel导出 不带时间
 * @param {*} res
 */
 export const exportExcelFile2 = (res = {}, name) => {
  const blob = new Blob([res], {
    type: 'application/octet-stream'
  }); //, { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' }
  const downloadElement = document.createElement('a');
  const href = window.URL.createObjectURL(blob);
  downloadElement.href = href;
  //cms合代码注意 兼容ie
  downloadElement.download = name + '.xls'; //文件名（自己随意设置）
  document.body.appendChild(downloadElement);
  if (!!window.ActiveXObject || 'ActiveXObject' in window || navigator.userAgent.indexOf('Edge') > -1) {
    window.navigator.msSaveOrOpenBlob(blob, downloadElement.download);
  } else {
    downloadElement.click();
  }
  //cms end
  document.body.removeChild(downloadElement); // 下载完成移除元素
  window.URL.revokeObjectURL(href);
};

/**
 * 导出文件
 * type 文件后缀名
 * name 文件名
 * @param {*} res
 */
export const exportFile = (res = {}, name, type = '') => {
  const blob = new Blob([res], {
    type: 'application/octet-stream'
  }); //, { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' }
  const downloadElement = document.createElement('a');
  const href = window.URL.createObjectURL(blob);
  downloadElement.href = href;
  //cms合代码注意 兼容ie
  if (type == '') {
    downloadElement.download = name;
  } else {
    downloadElement.download = name + '.' + type; //文件名（自己随意设置）
  }

  document.body.appendChild(downloadElement);
  if (!!window.ActiveXObject || 'ActiveXObject' in window || navigator.userAgent.indexOf('Edge') > -1) {
    window.navigator.msSaveOrOpenBlob(blob, downloadElement.download);
  } else {
    downloadElement.click();
  }
  //cms end
  document.body.removeChild(downloadElement); // 下载完成移除元素
  window.URL.revokeObjectURL(href);
};

/**
 * zip导出
 * @param {*} res
 */
export const exportZipFile = (res = {}, name) => {
  const blob = new Blob([res], {
    type: 'application/octet-stream'
  }); //, { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' }
  const downloadElement = document.createElement('a');
  const href = window.URL.createObjectURL(blob);
  downloadElement.href = href;

  //cms合代码注意 兼容ie
  downloadElement.download = name + formatdate(new Date(), 1) + '.zip'; //文件名（自己随意设置）
  document.body.appendChild(downloadElement);
  if (!!window.ActiveXObject || 'ActiveXObject' in window || navigator.userAgent.indexOf('Edge') > -1) {
    window.navigator.msSaveOrOpenBlob(blob, downloadElement.download);
  } else {
    downloadElement.click();
  }
  //cms end
  document.body.removeChild(downloadElement); // 下载完成移除元素
  window.URL.revokeObjectURL(href);
};

export function formatdate(data, t) {
  var d = data;
  var year = d.getFullYear();
  var months = d.getMonth() + 1;
  var month = months < 10 ? '0' + months : '' + months;
  var day = d.getDate() < 10 ? '0' + d.getDate() : '' + d.getDate();
  var hh = d.getHours();
  var mm = d.getMinutes();
  const ss = d.getSeconds();

  if (t == 1) {
    return year + '-' + month + '-' + day;
  } else {
    return year + '-' + month + '-' + day + ' ' + hh + ':' + mm + ':' + ss;
  }
}

export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null;
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}';
  let date;
  if (typeof time === 'object') {
    date = time;
  } else {
    if (('' + time).length === 10) time = parseInt(time) * 1000;
    date = new Date(time);
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  };
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key];
    if (key === 'a') return ['一', '二', '三', '四', '五', '六', '日'][value - 1];
    if (result.length > 0 && value < 10) {
      value = '0' + value;
    }
    return value || 0;
  });
  return time_str;
}

/**
 * 将对象转化为数组[{ fieldName: 'xxx', value: 'xxx' }, ...]的格式
 */
export function objectIntoList(obj) {
  let arimsArr = [];
  for (let [key, val] of Object.entries(obj)) {
    let param = {
      fieldName: camelcase(key),
      value: val
    };
    arimsArr.push(param);
  }
  return arimsArr;
}
/**
 * JSON对象的key值转换为驼峰式
 * @param {*} obj
 */
export function jsonToHump(obj) {
  if (obj instanceof Array) {
    obj.forEach((v, i) => {
      jsonToHump(v);
    });
  } else if (obj instanceof Object) {
    Object.keys(obj).forEach(key => {
      var newKey = camelcase(key);
      if (newKey !== key) {
        obj[newKey] = obj[key];
        delete obj[key];
      }
      jsonToHump(obj[newKey]);
    });
  }
}
// 驼峰转换  RO_NO --> roNo
export function camelcase(str) {
  let arr = str.split('_');
  let upper = arr.map((val, index) => {
    let lowStr = val.toLowerCase();

    if (index) {
      lowStr = lowStr.charAt(0).toLocaleUpperCase() + lowStr.slice(1);
    }

    return lowStr;
  });

  return upper.join('');
}

// 单个对象key转驼峰 有返回值,不改变传入参数
export function camelCaseObject(obj) {
  function camelcase(str) {
    let arr = str.split('_');
    if (arr.length > 1) {
      let upper = arr.map((val, index) => {
        let lowStr = val.toLowerCase();
        if (index) {
          lowStr = lowStr.charAt(0).toLocaleUpperCase() + lowStr.slice(1);
        }
        return lowStr;
      });
      return upper.join('');
    } else {
      return str;
    }
  }
  const newObj = {};
  const keys = Object.keys(obj);
  keys.forEach((key, i) => {
    newObj[camelcase(key)] = obj[key];
  });
  return newObj;
}
// 保留有效数字
export function retainValidNumbers(number, saveNumber = 2) {
  return Number(number.toFixed(saveNumber));
}
export function getEmployeeList() {
  return new Promise((resolve, reject) => {
    queryEmployees()
      .then(res => {
        let itemList = [];
        if (res.resultCode === 200) {
          itemList = res.data.map(x => ({
            value: x.employeeNo,
            text: x.employeeName
          }));
        }
        resolve(itemList);
      })
      .catch(err => {
        reject(err);
      });
  });
}

// 精度计算
export function setRound(val) {
  let precision = sessionStorage.getItem('precision');
  let settlementType = sessionStorage.getItem('settlementType');
  let resultVal = '';
  val = parseFloat(val);
  if (precision == '80651001') {
    // 元
    if (settlementType == '80641001') {
      // 四舍五入 （整数）
      // resultVal = parseFloat(val).toFixed(0);
      resultVal = Math.round(val);
    } else if (settlementType == '80641002') {
      // 只舍不入 (整数)
      resultVal = parseInt(val);
    } else if (settlementType == '80641003') {
      // 只入不舍 (保留整数位)
      resultVal = Math.ceil(val);
    }
  } else if (precision == '80651002') {
    // 角
    if (settlementType == '80641001') {
      // 四舍五入
      resultVal = val.toFixed(1);
    } else if (settlementType == '80641002') {
      // 只舍不入
      var tag = '.';
      var str = val + '';
      if (str.indexOf(tag) == -1) {
        resultVal = val.toFixed(1);
      } else {
        resultVal = parseFloat(str.substring(0, str.lastIndexOf('.') + 2));
      }
    } else if (settlementType == '80641003') {
      // 只入不舍
      var bb = val + '';
      var dian = bb.indexOf('.');
      if (dian == -1) {
        resultVal = val.toFixed(1);
      } else {
        var cc = bb.substring(dian + 1, bb.length);
        if (cc.length >= 2) {
          resultVal = bb.split('.')[0] + '.' + (cc[1] > 0 ? +cc[0] + 1 : cc[0]);
        } else {
          resultVal = val.toFixed(1);
        }
      }
    }
  } else if (precision == '80651003') {
    // 分
    resultVal = val.toFixed(2);
  } else {
    resultVal = Number(val).toFixed(2);
  }
  return resultVal;
}
/**
 * 数组对象去重
 * @param {Array}  arr    要去重的数组对象
 * @param {String} key    对象中的唯一标识符
 *
 * @return {Array} 去重后的数组
 */
export function arrayObjDeWeight(arr, key) {
  let newArr = JSON.parse(JSON.stringify(arr)),
    obj = {};
  newArr = newArr.reduce((item, next) => {
    obj[next[key]] ? '' : (obj[next[key]] = item.push(next));
    return item;
  }, []);
  return newArr;
}

//格式化时间为年-月-日
export function formatdateByDay(dataString) {
  if (dataString == null || dataString == '') {
    return '';
  }
  //let data = new Date(dataString);
  //return formatdate(data, 1);
  return moment(dataString).format('YYYY-MM-DD');
}

//格式化时间为年-月-日 时:分:秒
export function formatdateByTime(dataString) {
  if (dataString == null || dataString == '') {
    return '';
  }
  return moment(dataString).format('YYYY-MM-DD HH:mm:ss');
  //let data = new Date(dataString);
  //return formatdate(data, 2);
}
//增加一天
export function addDate(time) {
  //日期格式
  Date.prototype.format = function (format) {
    var date = {
      'M+': this.getMonth() + 1,
      'd+': this.getDate(),
      'h+': this.getHours(),
      'm+': this.getMinutes(),
      's+': this.getSeconds(),
      'q+': Math.floor((this.getMonth() + 3) / 3),
      'S+': this.getMilliseconds()
    };
    if (/(y+)/i.test(format)) {
      format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    for (var k in date) {
      if (new RegExp('(' + k + ')').test(format)) {
        format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? date[k] : ('00' + date[k]).substr(('' + date[k]).length));
      }
    }
    return format;
  };
  //加一天
  var timestamp = Date.parse(new Date(time));
  timestamp = timestamp / 1000;
  timestamp += 86400; //加一天
  var newTime = new Date(timestamp * 1000).format('yyyy-MM-dd hh:mm:ss');
  return newTime;
}

// 数组合并
export function integration(list1, list2, Key) {
  if (list1.length < list2.length) {
    let list = list1;
    list1 = list2;
    list2 = list;
  }
  let length1 = list1.length;
  let length2 = list2.length;
  let arr = [];
  for (let i = 0; i < length1; i++) {
    for (let j = 0; j < length2; j++) {
      //判断添加的数组是否为空了
      if (list1.length > 0) {
        if (list1[i][Key] === list2[j][Key]) {
          arr.push(list1[i]);
          list1.splice(i, 1); //利用splice函数删除元素，从第i个位置，截取长度为1的元素
          length1--;
          // console.log(list2[j]);//重复元素
        }
      }
    }
  }
  for (let n = 0; n < list2.length; n++) {
    list1.push(list2[n]);
  }
  list1.forEach((x, i) => {
    arr.map(y => {
      if (x[Key] === y[Key]) {
        x = {
          ...x,
          ...y
        };
        list1.splice(i, 1, x);
      }
    });
  });
  return list1;
  // console.log(list1)
}

/**
 * 数组提取合并
 * @param {Array}  arr    要提取的数组数组
 * @param {String} key    对象中的唯一标识符
 * @param {String} keys    需要相加的参数数组
 *
 * @return {Array} 提取后的数组
 */
export function integrations(arr = [], Key, keys = []) {
  // console.log(list1)
  if (arr.length === 0) {
    return [];
  }
  let list = [];
  arr.map(x => {
    if (x.length > 0) {
      x.map(y => {
        if (y[Key]) {
          list.push(y);
        }
      });
    }
  });
  //去重
  let newArr = JSON.parse(JSON.stringify(list)),
    obj = {};
  newArr = newArr.reduce((item, next) => {
    obj[next[Key]] ? '' : (obj[next[Key]] = item.push(next));
    return item;
  }, []);
  // debugger
  newArr.forEach(x => {
    keys.map(k => {
      x[k] = 0;
      list.map(j => {
        if (x[Key] === j[Key]) {
          let a = x[k] || 0;
          let b = j[k] || 0;
          x[k] = a + b;
        }
      });
    });
  });
  return newArr;
}

// 求百分比
export function GetPercent(num, total) {
  num = parseFloat(num);
  total = parseFloat(total);
  if (isNaN(num) || isNaN(total)) {
    return '-';
  }
  return total <= 0 ? '0%' : Math.round((num / total) * 10000) / 100.0 + '%';
}

/**
 * 计算全部
 * @param {Array} list1    对应的table的columns
 * @param {Array} list2    要提取的数组数组
 *
 * @return {Object} 提取后的obj
 */
//
export function computedAll(list1, list2) {
  let obj = {};
  list1.forEach(x => {
    if (x.children && x.children.length > 0) {
      x.children.forEach(x1 => {
        list2.map(y => {
          let a = obj[x1.dataIndex] || 0;
          let b = y[x1.dataIndex] || 0;
          obj[x1.dataIndex] = a + b;
        });
      });
    } else if (x.dataIndex) {
      list2.map(y => {
        let a = obj[x.dataIndex] || 0;
        let b = y[x.dataIndex] || 0;
        obj[x.dataIndex] = a + b;
      });
    }
  });
  return obj;
}
/**
 * 计算全部
 * @param {Array} arr    需要拼接的数组
 * @param {String} key    需要拼接中间字符,不传则直接拼接
 * @param {String} connect    需要拼接中间字符,默认','
 *
 * @return {String} 拼接后的字符串
 */
//
export function getTextByJs(arr, key, connect) {
  var str = '';
  if (arr.length === 0) {
    return '';
  }
  if (!connect) {
    connect = ',';
  }
  if (key) {
    for (var i = 0; i < arr.length; i++) {
      str += arr[i][key] + connect;
    }
  } else {
    for (var i = 0; i < arr.length; i++) {
      str += arr[i] + connect;
    }
  }
  //去掉最后一个逗号(如果不需要去掉，就不用写)
  if (str.length > 0) {
    str = str.substr(0, str.length - 1);
  }
  return str;
}

/**
 * 判断参数是否勾选
 * @param {String}  key    需要获取的key，例如1211
 * @param {String} selectedKey    需要判断是否选中的参数,例如12111019
 * @return {boolean} 返回true代表selectedKey被勾选，相反则未勾选
 */
export function isAuthorized(key, selectedKey) {
  let personParam = localStorage.getItem(key);
  if (!!personParam && personParam != null && personParam != '') {
    if (personParam.indexOf(selectedKey) < 0) {
      return false;
    } else {
      return true;
    }
  } else {
    return false;
  }
}

/**
 * @description: 查找表单中的某一项
 * @param { formList Array 表单列表, fieldName String 字段名}
 * @return { Object/null }
 * @author: 何兴家
 */
export function findFormItem(formList, fieldName) {
  return formList.find(item => item.fieldName === fieldName) || null;
}

/**
 * @description: 查找table中的某一列
 * @param { columns Array table列表, dataIndex String 字段名}
 * @return { Object/null }
 * @author: 何兴家
 */
export function findTableItem(columns, dataIndex) {
  return columns.find(item => item.dataIndex === dataIndex) || null;
}

export function dateFormat(pattern, date) {
  var o = {
    'M+': date.getMonth() + 1, // 月份
    'd+': date.getDate(), // 日
    'h+': date.getHours(), // 小时
    'm+': date.getMinutes(), // 分
    's+': date.getSeconds(), // 秒
    'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
    S: date.getMilliseconds() // 毫秒
  };
  let fmt = pattern;
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
  }
  for (var k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length));
    }
  }
  return fmt;
}
export function downloadUrl(url, filename) {
  const anchor = document.createElement('a');
  anchor.href = url;
  anchor.setAttribute('download', filename);
  anchor.innerHTML = 'downloading...';
  anchor.style.display = 'none';
  document.body.appendChild(anchor);
  anchor.click();
  //cms end
  document.body.removeChild(anchor); // 下载完成移除元素
  window.URL.revokeObjectURL(anchor.href);
}

export function copyUpdateData(oldData, newData) {
  for (let key in newData) {
    oldData[key] = newData[key];
  }
  oldData['updatedAt'] = null;
  oldData['updatedBy'] = null;
  return oldData;
}
// 格式化金额
export function formatMoney(str, n) {
  //s:传入的float数字 ，n:希望返回小数点几位
  n = n > 0 && n <= 20 ? n : 2;

  str = parseFloat((str + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";

  let l = str.split(".")[0].split("").reverse(),
    r = str.split(".")[1],
    t = "";
  for (i = 0; i < l.length; i++) {
    t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
  }
  return t.split("").reverse().join("") + "." + r;
}
// 还原格式化金额
export function returnMoney(str) {
  return parseFloat(str.replace(/[^\d\.-]/g, ""));
}
